import React, { useContext, useEffect, useRef, useState } from 'react';
import '../styles/dist/dayjob.css';
import type { InputRef } from 'antd';
import axios from '../axios';
import type { UploadProps } from 'antd';
import { Upload } from 'antd';
import moment from 'moment';
import {
  Button,
  Form,
  Input,
  Popconfirm,
  Table,
  DatePicker,
  message,
} from 'antd';
import type { FormInstance } from 'antd/es/form';
import { PlusCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { Col, Row } from 'antd';
import { importsExcel, exportExcel } from '@/until/excel';
import { Select } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { Radio } from 'antd';
import type { SizeType } from 'antd/es/config-provider/SizeContext';
import type { ColumnsType } from 'antd/es/table';
import dayjs, { Dayjs } from 'dayjs';
import TextArea from 'antd/lib/input/TextArea';

const EditableContext = React.createContext<FormInstance<any> | null>(null);

const { Option } = Select;

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

interface Values {
  title: string;
  description: string;
  modifier: string;
}

const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const config = {
  rules: [
    { type: 'object' as const, required: true, message: 'Please select time!' },
  ],
};
const rangeConfig = {
  rules: [
    { type: 'array' as const, required: true, message: 'Please select time!' },
  ],
};

interface Item {
  key: string;
  name: string;
  age: string;
  address: string;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
  scheduleName: string;
  scheduleType: string;
  upTime: String;
  createTime: String;
  createPeople: String;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

export default function dayJob() {
  const [defaultValue, setDefaultValue] = useState<string>('全部');
  const [list, setList] = useState<string[]>([]);
  const props: UploadProps = {
    name: 'file',
    accept: '.xlsx,.xls',
    headers: {
      authorization: 'authorization-text',
    },
    onChange: (event) => {
      if (event.file.status === 'done') {
        const file = event.file;
        importsExcel(file.originFileObj).then(
          function (data) {
            setList(data as any);
            addExcel(data as any);
            console.log(data);
          },
          function (err) {
            console.log(err);
          },
        );
      }
    },
  };
  const addExcel = async (lists: any) => {
    let {
      data: { code, msg },
    } = await axios.post('/addManyExcel', lists);
    if (code === 200) {
      message.success(msg);
      getTable();
    }
  };

  const [searchType, setSearchType] = useState<string>('');

  const handleChange = (value: string) => {
    setSearchType(value);
    setDefaultValue(value);
    console.log(`selected ${value}`);
  };
  const onFinish1 = (fieldsValue: any) => {
    // Should format date value before submit.
    const rangeValue = fieldsValue['range-picker'];
    const values = {
      ...fieldsValue,
      'range-picker': [
        rangeValue[0].format('YYYY-MM-DD'),
        rangeValue[1].format('YYYY-MM-DD'),
      ],
    };
    console.log('Received values of form: ', values);
  };

  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };
  const [dataSource, setDataSource] = useState<DataType[]>([]);
  const handleDelete = async (id: React.Key) => {
    let {
      data: { msg, code },
    } = await axios.get('/deleteSchedule', { params: { id: id } });
    if (code === 200) {
      getTable();
      message.success(msg);
    }
  };

  useEffect(() => {
    getTable();
  }, []);
  const getTable = async () => {
    let {
      data: { code, data },
    } = await axios.get('/getTable', { params: { searchName, searchType } });
    if (code === 200) {
      setDataSource(data.reverse());
      setExcelList(data);
      setSearchName('');
      setSearchType('');
    }
  };

  const defaultColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex: string;
  })[] = [
    {
      title: '日程名称',
      dataIndex: 'scheduleName',
    },
    {
      title: '类型',
      dataIndex: 'scheduleType',
    },
    {
      title: '修改时间',
      dataIndex: 'upTime',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createPeople',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (
        _,
        record: {
          _id?: any;
          scheduleName?: string;
          scheduleType?: string;
          upTime?: string;
          createTime?: string;
          createPeople?: string;
        },
      ) =>
        dataSource.length >= 1 ? (
          <div>
            <Popconfirm
              title="确定要删除此日程吗?"
              onConfirm={() => handleDelete(record._id)}
            >
              <a>删除</a>
            </Popconfirm>
            <a
              style={{ marginLeft: '10px' }}
              onClick={() =>
                upSchedule(
                  record as {
                    _id: any;
                    scheduleName: string;
                    scheduleType: string;
                    upTime: string;
                    createTime: string;
                    createPeople: string;
                  },
                )
              }
            >
              编辑
            </a>
          </div>
        ) : null,
    },
  ];

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const allNew = async () => {
    let {
      data: { code, data },
    } = await axios.get('/getTable');
    if (code === 200) {
      setDataSource(data.reverse());
      setDefaultValue('全部');
      setSearchName('');
    }
  };

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        // handleSave,
      }),
    };
  });
  const [searchName, setSearchName] = useState<string>('');
  const [form] = Form.useForm();

  const onGenderChange = (value: string) => {
    setScheduleType(value);
    switch (value) {
      case '正常班':
        form.setFieldsValue({ note: '正常班' });
        return;
      case '加班':
        form.setFieldsValue({ note: '加班' });
        return;
      case '夜班':
        form.setFieldsValue({ note: '夜班' });
    }
  };
  const [scheduleName, setScheduleName] = useState<string>('123');
  const [scheduleType, setScheduleType] = useState<string>('');
  const [createTime, setCreateTime] = useState<string>('');
  const [upTime, setUpTime] = useState<string>('');
  const [pickerUptime, setPickerUptime] = useState<any>(
    moment('2024-06-16', 'YYYY-MM-DD'),
  );
  const [pickerCreateTime, setPickerCreateTime] = useState<any>(
    moment('2024-06-16', 'YYYY-MM-DD'),
  );
  const onReset = () => {
    form.resetFields();
  };
  const lthUpShedule = async () => {
    let {
      data: { code, msg },
    } = await axios.post('/upSchedule', {
      _id: oneData,
      scheduleName,
      scheduleType,
      upTime,
      createTime,
    });
    if (code === 200) {
      message.success(msg);
      setIsUpOpen(false);
      getTable();
    }
  };
  const [header, setHeader] = useState<any>([
    {
      title: '日程名称',
      dataIndex: 'scheduleName',
      key: 'scheduleName',
    },
    {
      title: '类型',
      dataIndex: 'scheduleType',
      key: 'scheduleType',
    },
    {
      title: '修改时间',
      dataIndex: 'upTime',
      key: 'upTime',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createPeople',
      key: 'createPeople',
    },
  ]);
  const [excelList, setExcelList] = useState<any>([]);
  const addSchedule = async () => {
    let {
      data: { msg, code },
    } = await axios.post('/addSchedule', {
      scheduleName,
      scheduleType,
      createTime,
      upTime,
    });
    if (code === 200) {
      message.success(msg);
      setScheduleName('');
      setScheduleType('');
      setCreateTime('');
      setUpTime('');
      setIsModalOpen(false);
      getTable();
    }
  };
  const [oneData, setOneData] = useState<string>('');
  const upSchedule = (record: {
    _id?: any;
    scheduleName: string;
    scheduleType: string;
    upTime: string;
    createTime: string;
  }) => {
    setOneData(record._id);
    form.setFieldsValue({ note: record.scheduleName });
    form.setFieldsValue({ gender: record.scheduleType });
    setIsUpOpen(true);
  };
  const [rangeTime, setRangeTime] = useState<any>(null);
  const dateChange = (date: any, dateString: any) => {
    console.log(dateString);
    setRangeTime(date);
    const dates = new Date();
    let dateHour = dates.getHours().toString().padStart(2, '0');
    let dateMinute = dates.getMinutes().toString().padStart(2, '0');
    let dateSecond = dates.getSeconds().toString().padStart(2, '0');
    setCreateTime(
      dateString[0] + ' ' + dateHour + ':' + dateMinute + ':' + dateSecond,
    );
    setUpTime(
      dateString[1] + ' ' + dateHour + ':' + dateMinute + ':' + dateSecond,
    );
  };

  const Ref = useRef<any>(null);
  const [isUpOpen, setIsUpOpen] = useState<boolean>(false);

  return (
    <div>
      <div className="dayJob-header">
        <Row>
          <Col span={6}>
            <label>日程名称：</label>
            <Input
              placeholder="输入日程名称"
              className="dayJob-header-input"
              value={searchName}
              onChange={(e) => {
                setSearchName(e.target.value);
              }}
            />
          </Col>
          <Col span={6}>
            <label>类型：</label>
            <Select
              className="dayJob-header-select"
              // defaultValue={defaultValue}
              value={defaultValue}
              style={{ width: 120 }}
              onChange={handleChange}
              optionLabelProp="label"
              options={[
                {
                  value: '正常班',
                  label: '正常班',
                },
                {
                  value: '加班',
                  label: '加班',
                },
              ]}
            />
          </Col>
          <Col span={6}>
            <Button
              type="primary"
              style={{ borderRadius: '10px' }}
              onClick={() => {
                getTable();
              }}
            >
              查询
            </Button>
          </Col>
          <Col span={6}>
            <Button
              style={{ borderRadius: '10px' }}
              onClick={() => {
                allNew();
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </div>
      <div>
        <div className="dayJob-button">
          <div>
            <Button
              type="primary"
              style={{ marginBottom: 16 }}
              onClick={showModal}
            >
              <PlusCircleOutlined />
              新建日程
            </Button>
          </div>
          <div className="dayJob-buttons">
            <div style={{ display: 'inline-block' }}>
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>导入</Button>
              </Upload>
            </div>
            <Button
              onClick={() => {
                exportExcel(header, excelList, '日程计划表.xlsx');
              }}
            >
              <UploadOutlined />
              导出
            </Button>
          </div>
        </div>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns as ColumnTypes}
        />
      </div>
      <div
        style={{
          width: '100%',
          height: '100vh',
          background: 'rgba(0,0,0,0.3)',
          position: 'absolute',
          top: '0',
          left: '0',
          display: isModalOpen ? 'block' : 'none',
        }}
      >
        <div
          id="lth-addTable"
          style={{
            width: '900px',
            height: '600px',
            display: 'flex',
            alignItems: 'center',
            borderRadius: '15px',
            backgroundColor: 'white',
            position: 'absolute',
            top: '20%',
            left: '25%',
          }}
        >
          <div style={{ height: '480px', marginLeft: '40px' }}>
            <Form
              {...layout}
              form={form}
              name="control-hooks"
              // onFinish={onFinish}
            >
              <Form.Item name="note" rules={[{ required: true }]}>
                <h2
                  style={{
                    textAlign: 'center',
                    fontWeight: '800',
                    fontSize: '30px',
                  }}
                >
                  添加日程
                </h2>
              </Form.Item>
              <Form.Item
                name="note"
                label="日程名称"
                rules={[{ required: true }]}
              >
                <Input
                  value={scheduleName}
                  onChange={(e) => {
                    setScheduleName(e.target.value);
                  }}
                />
              </Form.Item>
              <Form.Item
                name="gender"
                label="类型"
                rules={[{ required: true }]}
              >
                <Select
                  placeholder="请选择类型"
                  onChange={onGenderChange}
                  allowClear
                >
                  <Option value="正常班">正常班</Option>
                  <Option value="加班">加班</Option>
                  <Option value="夜班">夜班</Option>
                </Select>
              </Form.Item>
              <Form.Item name="" label="描述" rules={[{ required: true }]}>
                <TextArea rows={4} />
              </Form.Item>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) =>
                  prevValues.gender !== currentValues.gender
                }
              >
                {({ getFieldValue }) =>
                  getFieldValue('gender') === 'other' ? (
                    <Form.Item
                      name="customizeGender"
                      label="Customize Gender"
                      rules={[{ required: true }]}
                    >
                      <Input />
                    </Form.Item>
                  ) : null
                }
              </Form.Item>
              <Form.Item {...tailLayout}>
                <Button htmlType="button" onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
              <Form
                name="time_related_controls"
                {...formItemLayout}
                onFinish={onFinish1}
              >
                <Form.Item
                  name="range-picker"
                  label="日期安排"
                  {...rangeConfig}
                >
                  <RangePicker onChange={dateChange} />
                </Form.Item>
                <Form.Item
                  wrapperCol={{
                    xs: { span: 24, offset: 0 },
                    sm: { span: 16, offset: 8 },
                  }}
                  style={{
                    position: 'absolute',
                    left: '70%',
                    width: '250px',
                    top: '85%',
                  }}
                >
                  <Button
                    type="primary"
                    onClick={() => {
                      setIsModalOpen(false);
                    }}
                  >
                    取消
                  </Button>
                  <div style={{ width: '20px', display: 'inline-block' }}></div>
                  <Button
                    type="primary"
                    onClick={() => {
                      addSchedule();
                    }}
                  >
                    添加
                  </Button>
                </Form.Item>
              </Form>
            </Form>
          </div>
        </div>
      </div>
      <div
        style={{
          width: '100%',
          height: '100vh',
          background: 'rgba(0,0,0,0.3)',
          position: 'absolute',
          top: '0',
          left: '0',
          display: isUpOpen ? 'block' : 'none',
        }}
      >
        <div
          id="lth-addTable"
          style={{
            width: '900px',
            height: '600px',
            display: 'flex',
            alignItems: 'center',
            borderRadius: '15px',
            backgroundColor: 'white',
            position: 'absolute',
            top: '20%',
            left: '25%',
          }}
        >
          <div style={{ height: '480px', marginLeft: '40px' }}>
            <Form
              {...layout}
              form={form}
              name="control-hooks"
              // onFinish={onFinish}
            >
              <Form.Item name="note" rules={[{ required: true }]}>
                <h2
                  style={{
                    textAlign: 'center',
                    fontWeight: '800',
                    fontSize: '30px',
                  }}
                >
                  修改日程
                </h2>
              </Form.Item>
              <Form.Item
                name="note"
                label="日程名称"
                rules={[{ required: true }]}
              >
                <Input
                  value={scheduleName}
                  onChange={(e) => {
                    setScheduleName(e.target.value);
                  }}
                />
              </Form.Item>
              <Form.Item
                name="gender"
                label="类型"
                rules={[{ required: true }]}
              >
                <Select
                  placeholder="请选择类型"
                  onChange={onGenderChange}
                  allowClear
                >
                  <Option value="正常班">正常班</Option>
                  <Option value="加班">加班</Option>
                  <Option value="夜班">夜班</Option>
                </Select>
              </Form.Item>
              <Form.Item name="" label="描述" rules={[{ required: true }]}>
                <TextArea rows={4} />
              </Form.Item>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) =>
                  prevValues.gender !== currentValues.gender
                }
              >
                {({ getFieldValue }) =>
                  getFieldValue('gender') === 'other' ? (
                    <Form.Item
                      name="customizeGender"
                      label="Customize Gender"
                      rules={[{ required: true }]}
                    >
                      <Input />
                    </Form.Item>
                  ) : null
                }
              </Form.Item>
              <Form.Item {...tailLayout}>
                <Button htmlType="button" onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
              <Form
                name="time_related_controls"
                form={form}
                ref={Ref}
                {...formItemLayout}
                onFinish={onFinish1}
              >
                <Form.Item
                  name="range-picker"
                  label="活动日期"
                  {...rangeConfig}
                >
                  <RangePicker
                    onChange={dateChange}
                    value={rangeTime}
                    // value={[pickerUptime, pickerCreateTime]}
                    defaultValue={[pickerUptime, pickerCreateTime]}
                  />
                </Form.Item>
                <Form.Item
                  wrapperCol={{
                    xs: { span: 24, offset: 0 },
                    sm: { span: 16, offset: 8 },
                  }}
                  style={{
                    position: 'absolute',
                    left: '70%',
                    width: '250px',
                    top: '85%',
                  }}
                >
                  <Button
                    type="primary"
                    onClick={() => {
                      setIsUpOpen(false);
                    }}
                  >
                    取消
                  </Button>
                  <div style={{ width: '20px', display: 'inline-block' }}></div>
                  <Button
                    type="primary"
                    onClick={() => {
                      lthUpShedule();
                    }}
                  >
                    修改
                  </Button>
                </Form.Item>
              </Form>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
}
